package com.hmdp.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author jie
 * @version 1.0 2024-12-29
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求的token
        String token = request.getHeader("authorization");
        if (!StrUtil.isBlank(token)) {
            // 2. 判断用户信息是否存在
            String key = RedisConstants.LOGIN_USER_KEY + token;
            Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(key);
            if (!entries.isEmpty()) {
                // 3. 刷新token
                stringRedisTemplate.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
                // 4. 将用户信息放入ThreadLocal中
                UserDTO userDTO = BeanUtil.fillBeanWithMap(entries, new UserDTO(), false);
                UserHolder.saveUser(userDTO);
            }
        }
        // 放行
        return true;
    }
}
